<template>
	<div
		class="flex min-h-screen flex-col md:items-center items-start justify-start bg-gray-50 dark:bg-gray-900 p-4"
	>
    <AppHeader
			@back="handleBack"
			class="md:hidden w-full bg-gray-50"
			:right-placeholder="true"
		>
			<template #center>
				<h1 class="text-base font-bold text-gray-900 dark:text-white">
					登录账号 
				</h1>
			</template>
		</AppHeader>
		<div
			class="w-full max-w-md p-6 md:p-8 space-y-6 bg-white dark:bg-gray-800 rounded-lg shadow-md"
		>
			<div class="text-center">
				<h1 class="text-3xl font-bold text-gray-900 dark:text-white">
					欢迎回来
				</h1>
				<p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
					还没有账户？
					<router-link
						to="/register"
						class="font-medium text-emerald-600 hover:text-emerald-500 dark:text-emerald-400 dark:hover:text-emerald-300"
					>
						立即注册
					</router-link>
				</p>
			</div>

			<form class="space-y-6" @submit.prevent="onLoginSubmit">
				<div>
					<label
						for="username"
						class="block text-sm font-medium text-gray-700 dark:text-gray-300"
						>用户名</label
					>
					<input
						v-model="form.username"
						id="username"
						name="username"
						type="text"
						autocomplete="username"
						required
						class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-emerald-500 focus:border-emerald-500"
						placeholder="请输入用户名"
					/>
				</div>

				<div>
					<label
						for="password"
						class="block text-sm font-medium text-gray-700 dark:text-gray-300"
						>密码</label
					>
					<input
						v-model="form.password"
						id="password"
						name="password"
						type="password"
						autocomplete="current-password"
						required
						class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-emerald-500 focus:border-emerald-500"
						placeholder="请输入密码"
					/>
				</div>

				<div class="pt-2">
					<SliderCaptcha
						ref="captchaRef"
						@success="onCaptchaSuccess"
					/>
				</div>

				<div>
					<button
						@click="onLoginSubmit"
						type="submit"
						:disabled="isLoading"
						class="w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 disabled:bg-gray-400 dark:disabled:bg-gray-600 disabled:cursor-not-allowed transition-colors"
					>
						<span v-if="isLoading">登录中...</span>
						<span v-else>登 录</span>
					</button>
				</div>
			</form>
			<div class="relative my-6">
				<div class="absolute inset-0 flex items-center">
					<div class="w-full border-t border-gray-300 dark:border-gray-600"></div>
				</div>
				<div class="relative flex justify-center text-sm">
					<span class="px-2 bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400">
						或通过以下方式登录
					</span>
				</div>
			</div>

			<div class="flex justify-center items-center space-x-4">
				<!-- QQ 登录 -->
				<span id="qqLoginBtn" v-show="false"></span>
				<div
					@click="onQQLogin"
					class="p-2 rounded-full border border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer transition-colors"
				>
					<QQIcon class="w-4 h-4" />
				</div>

				<!-- 微信登录 -->
				<div
					@click="onWeiXinLogin"
					class="p-2 rounded-full border border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer transition-colors"
				>
					<WXIcon class="w-4 h-4" />
				</div>
				<!-- 微信扫码容器 (如果需要) -->
				<div id="login_container" class="hidden"></div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { md5 } from "js-md5";
import { useUserStore } from "@/store/modules/user";
import SliderCaptcha from "@/components/SilderCaptcha.vue";
import { useModal } from "@/hooks/useModal";
import ToastModal from "@/modal/components/ToastModal.vue";
import AppHeader from "@/components/AppHeader.vue";
import brodacast from "@/utils/broadcast";
import { LOGIN_TYPE_QQ, LOGIN_TYPE_WX } from "@/constants";
import QQIcon from "@/components/icon/QQIcon.vue";
import WXIcon from "@/components/icon/WXIcon.vue";
import {
	getWXLoginData,
	getWXLoginToken,
	getWXLoginUserInfo,
} from "@/apis/index";



const modal = useModal();

const router = useRouter();
const route = useRoute()
const userStore = useUserStore();

const form = reactive({
	username: "",
	password: "",
});

const handleBack = () => {
	router.back();
};

const isLoading = ref(false);
const isCaptchaVerified = ref(false);
const captchaRef = ref<InstanceType<typeof SliderCaptcha> | null>(null);

const onCaptchaSuccess = () => {
	isCaptchaVerified.value = true;
};

const showToast = (message: string) => {
	modal.show(
		ToastModal,
		{ message },
		{
			position: "bottom",
			animationType: "slide-up",
			showOverlay: false,
			closeOnClickOverlay: false,
			duration: 1000,
		}
	);
};

const QQ_LOGIN_URL = 'https://graph.qq.com/oauth2.0/authorize?client_id=101998494&response_type=token&scope=all&redirect_uri=https%3A%2F%2Fimooc-front.lgdsunday.club%2Flogin';
const oauthLogin = async (loginType: string, data: any) => {
	isLoading.value = true;
	try {
		await userStore.handleLogin({
			loginType,
			...data,
		});

		showToast(`登录成功`);
		const redirectUrl = route.query.redirect as string | undefined;
		router.replace(redirectUrl || "/");
	} catch (error: any) {
		showToast(`登录失败: ${error.message || "第三方登录出错"}`);
	} finally {
		isLoading.value = false;
	}
};

onMounted(() => {
	
	// QC.Login(
	// 	{
	// 		btnId: "qqLoginBtn",
	// 	},
	// 	(data: any, opts: any) => {
	// 		// 1. 注销，防止循环触发
	// 		// @ts-ignore
	// 		QC.Login.signOut();
	// 		// 2. 获取 accessToken
	// 		const accessToken = /access_token=((.*))&expires_in/.exec(
	// 			window.location.hash
	// 		)![1];
	// 		// 3. 准备数据
	// 		const oauthObj = {
	// 			nickname: data.nickname,
	// 			figureurl_qq_2: data.figureurl_qq_2,
	// 			accessToken,
	// 		};
	// 		// 4. 发送数据给主窗口
	// 		brodacast.send(oauthObj);
	// 		// 5. 移动端直接在本页面登录
	// 		oauthLogin(LOGIN_TYPE_QQ, oauthObj);
	// 		// 6. PC端关闭此回调窗口
	// 		window.close();
	// 	}
	// );
});

const onQQLogin = () => {
	window.open(
		QQ_LOGIN_URL,
		"oauth2Login_10609",
		"height=525,width=585, toolbar=no, menubar=no, scrollbars=no, status=no, location=yes, resizable=yes"
	);
	// 等待回调窗口的数据
	brodacast.wait().then(async (oauthObj: any) => {
		brodacast.clear();
		await oauthLogin(LOGIN_TYPE_QQ, oauthObj);
	});
};


if (window.location.search) {
	const codeMatch = /code=([^&]+)/.exec(window.location.search);
	if (codeMatch && codeMatch[1]) {
		brodacast.send({ code: codeMatch[1] });
		window.close();
	}
}

const onWeiXinLogin = async () => {
	try {
		const { appId, redirectUri, scope, state } = await getWXLoginData();
		window.open(
			`https://open.weixin.qq.com/connect/qrconnect?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`,
			"",
			"height=525,width=585, toolbar=no, menubar=no, scrollbars=no, status=no, location=yes, resizable=yes"
		);

		brodacast.wait().then(async ({ code }: any) => {
			brodacast.clear();
			// 这里假设你的 API 已经封装好了，可以处理后续流程
			// 为了简化，我们直接在前端完成后续请求，并最终调用 oauthLogin
			// 注意：在生产环境中，appSecret 不应暴露在前端！后续步骤应在后端完成。
			// const { access_token, openid } = await getWXLoginToken(appId, appSecret, code);
			// const { nickname, headimgurl } = await getWXLoginUserInfo(access_token, openid);
			
			// 我们假设后端有一个接口，接收 code 后完成所有操作
			// 所以我们直接把 code 传给 oauthLogin
			await oauthLogin(LOGIN_TYPE_WX, { code, state });
		});
	} catch (error: any) {
		showToast(`微信登录初始化失败: ${error.message}`);
	}
};



const onLoginSubmit = async () => {
	if (isLoading.value) return;

	isLoading.value = true;
	try {
		await userStore.handleLogin({
			username: form.username,
			// 在前端使用 md5 加密密码
			password: md5(form.password),
			loginType: "username", // 假设登录类型
		});
		showToast(`登录成功`);
		const redirectUrl = route.query.redirect as string | undefined;
		console.log(redirectUrl);
		if(redirectUrl){
			router.replace(redirectUrl);
		}else{
			router.replace("/"); 
		}
	} catch (error: any) {
		// 登录失败，给出提示
		showToast(`登录失败: ${error.message || "请检查您的用户名和密码"}`);
		// 重置滑块验证码
		isCaptchaVerified.value = false;
		captchaRef.value?.reset();
	} finally {
		isLoading.value = false;
	}
};
</script>
